package websocket

import (
	"awesomeTask/application/client"
	"awesomeTask/application/variable"
	"awesomeTask/commom/MessageHelper"
	"awesomeTask/config"
	"awesomeTask/system/event"
	"awesomeTask/system/helper"
	log2 "awesomeTask/system/log"
	"awesomeTask/system/safe"
	WsServer "awesomeTask/system/wsServer"
	"fmt"
	"github.com/gorilla/websocket"
	"net/http"
	"strings"
)

var wsObj *WsServer.WsServer

func RunWebScoket(port int) {
	ws := WsServer.WsServer{}
	wsObj = &ws
	ws.OnConnect(func(connection *websocket.Conn) {
		if checkSafe(ws.GetRequest(connection)) == false {
			connection.Close()
			log2.GetLogger().Warn("校验失败无效的clientToken")
			return
		}
		SendWebOne(connection, variable.ON_WS_RECORD_NODES, client.Nodes)
	})
	ws.OnMessage(func(connection *websocket.Conn, message string) {
		defer func() {
			if r := recover(); r != nil {
				log2.GetLogger().Error("无法解析的数据:" + message)
			}
		}()
		eventInfo := helper.JsonDecode(message)
		fmt.Println(eventInfo)
	})
	event.Register(variable.ON_LOG, func(args ...interface{}) {
		msg := args[0]
		SendWeb(ws, variable.ON_LOG, msg)
	})
	ws.OnStart(func() {
		event.Register("RecordNodeInfo", func(args ...interface{}) {
			eventInfo := args[0]
			SendWeb(ws, variable.ON_WS_RECORD_NODES, eventInfo)
		})
		event.Register(variable.ON_WS_NOTICE_DISCONNECTION, func(args ...interface{}) {
			uniqueId := args[0]
			SendWeb(ws, variable.ON_WS_NOTICE_DISCONNECTION, uniqueId)
		})

		event.Register(variable.ON_PUSH_TASK, func(args ...interface{}) {
			SendWeb(ws, variable.ON_PUSH_TASK, args[0])
		})
	})
	ws.Start(port, "console", false)

}
func parseUrl(url string) map[string]interface{} {
	urlInfo := strings.Split(url, "?")
	if len(urlInfo) < 2 {
		return map[string]interface{}{}
	}
	res := make(map[string]interface{})
	for _, item := range strings.Split(urlInfo[1], "&") {
		param := strings.Split(item, "=")
		if len(param) < 2 {
			continue
		}
		res[param[0]] = param[1]
	}
	return res
}
func checkSafe(req *http.Request) bool {
	params := parseUrl(req.RequestURI)
	if params["clientToken"] != config.GetConfigByKey("clientToken") {
		return false
	}
	return true
}
func SendWeb(ws WsServer.WsServer, event string, msg interface{}) {
	info := make(map[string]interface{})
	info["event"] = event
	info["msg"] = msg
	for _, item := range ws.GetConnections() {
		safe.Lock()
		item.WriteJSON(info)
		safe.Unlock()
	}

}
func SendWebOne(connection *websocket.Conn, event string, msg interface{}) {
	info := make(map[string]interface{})
	info["event"] = event
	info["msg"] = msg
	safe.Lock()
	connection.WriteJSON(info)
	safe.Unlock()
}
func SendToAll(event string, msg interface{}) {
	SendWeb(*wsObj, event, msg)
	fmt.Println(wsObj.GetConnections(), "connections===>")
}
func SendToAllNodes(event string, msg map[string]interface{}) {
	msg["realEvent"] = event
	MessageHelper.SendEvent(variable.ON_MASTER_SEND_TO_ALL_WS, msg, client.GetServerCon())
}
